/**
 *  This code is a part of Quadratix project.
 * Copyright (C) 2009 - 2010 Valery A. Ilychev aka Sarutobi (ilychev at gmail dot com)
 * 
 *  This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package ru.sarutobi.quadratix.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import ru.sarutobi.quadratix.AI;
import ru.sarutobi.quadratix.Board;
import ru.sarutobi.quadratix.Calculator;

public class Main extends JFrame implements ActionListener {

	private BoardPanel boardPane;

	private Board board;

	private NamePanel namePanel = new NamePanel();

	private int move = Board.WHITE;

	private AI ai;

	private Calculator calc;
	
	public Main() {
		super("Quadratix");
		setVisible(true);
		setResizable(true);		
		add(namePanel, BorderLayout.EAST);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent evt){
				System.exit(0);
			}
		});
		this.boardPane = new BoardPanel();
		JMenuBar menu = new JMenuBar();
		setJMenuBar(menu);
		JMenu file = new JMenu("Game");
		menu.add(file);
		JMenuItem newGame = new JMenuItem(new AbstractAction() {
			{
				putValue(Action.NAME, "New game");
			}

			public void actionPerformed(ActionEvent arg0) {
				setBoard(7);
			}
		});
		file.add(newGame);
		calc = Calculator.getCalculator(7);
		ai = new AI();
		setBoard(7);
		pack();
	}

	private void setBoard(int size) {
		if ( null != boardPane){
			remove(boardPane);
		}
		board = new Board(size);
		board.initialise();
		this.boardPane = new BoardPanel(board, this);
		add(boardPane);
		calc.setBoard(board.getBoard());
		ai.setCalc(calc);
		move = Board.WHITE;
		namePanel.resetScore();
		pack();
	}

	public void actionPerformed(ActionEvent e) {
		Fishka f = (Fishka) e.getSource();
		int x = f.getXpos();
		int y = f.getYpos();
		makeMove(x, y);
		if (!board.finished()){
			aiMove();
		} else {
			endGame();
		}
	}
	
	private void makeMove(int x, int y){
		if (board.Move(x, y, move)) {
			boardPane.visualize(x, y, move);
			calc.setBoard(board.getBoard());
			List<int[]> ret = calc.getSquares(x, y);
			for (Iterator<int[]> i = ret.iterator(); i.hasNext();) {
				final int[] tmp = i.next();
				final int c = move;
				if ((board.getPosition(tmp[0]) == board.getPosition(tmp[1]))
						&& (board.getPosition(tmp[0]) == board.getPosition(tmp[2]))
						&& (board.getPosition(tmp[0]) == board.getPosition(tmp[3]))) {
					Thread t = new Thread() {
						public void run() {
							boardPane.higlightSquare(tmp, c);
						}
					};
					t.start();
					
					int score = tmp[4];
					
					switch (move) {
					case Board.WHITE:
						namePanel.addWhiteScore(score);
						break;
					case Board.BLACK:
						namePanel.addBlackScore(score);
						break;
					}
				}
			}
			if (!board.finished()) {
				toggleMove();
				
			} else {
				endGame();
			}
		} else {
			System.err.println("Illegal move!");
		}
	}

	private void endGame() {
		namePanel.showWinner();
	}
	
	private void toggleMove(){
		move = (move == Board.WHITE) ? Board.BLACK : Board.WHITE;
		namePanel.setMove(move);
	}
	
	private void aiMove(){
		int t = ai.move(board.getBoard(), move);
		int bx = t % board.getSize();
		int by = t / board.getSize();
		//System.out.println(String.format("%d %d", bx, by));
		makeMove(bx, by);
	}
}
